package com.hebeiboruan.controller.system;
import com.hebeiboruan.dictionaries.service.DictionariesService;
import com.hebeiboruan.entity.DTO.system.SearchDictionariesDTO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hebeiboruan.dictionaries.listener.DictionariesListener;
import com.hebeiboruan.entity.system.Dictionaries;
import com.hebeiboruan.common.HttpMessage;
import com.hebeiboruan.common.exception.CommonException;
import java.time.LocalDateTime;
import com.hebeiboruan.common.exception.ServiceResultEnum;

import javax.servlet.http.HttpServletRequest;
import com.alibaba.excel.EasyExcel;
import java.net.URLEncoder;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import java.util.Arrays;
import java.io.IOException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hebeiboruan.common.uitl.LoggerUtil;
@RestController
@RequestMapping("/dictionaries")
public class DictionariesController {
    private static Logger log = LoggerFactory.getLogger(DictionariesController.class);
    private DictionariesService dictionariesService;
    @Autowired
    public void setDictionariesService(DictionariesService dictionariesService) {
    this.dictionariesService = dictionariesService;
    }

    @GetMapping("/getAllDictionaries/{page}/{limit}")
    public HttpMessage getAllDictionaries(@PathVariable Integer page,@PathVariable Integer limit){
        HttpMessage.isBlank(page,limit);
        Page<Dictionaries> parent = dictionariesService.page(new Page<>(page, limit), new QueryWrapper<Dictionaries>().isNull("parent"));
        parent.getRecords().forEach(item->{
            item.setSubset(dictionariesService.list(new QueryWrapper<Dictionaries>().eq("parent",item.getDictionariesNo())));
        });
        return  HttpMessage.data(parent);
    }

    @PostMapping("/searchDictionaries")
    public HttpMessage searchUser(SearchDictionariesDTO search){
    HttpMessage.isBlank(search.getPage(),search.getLimit());
    QueryWrapper<Dictionaries> wrapper=new QueryWrapper<>();
        if (search.getDictionariesName() != null) {
        wrapper.like("dictionaries_name",search.getDictionariesName());
        }
        if (search.getDictionariesKey() != null) {
        wrapper.like("dictionaries_key",search.getDictionariesKey());
        }
    return  HttpMessage.data(dictionariesService.page(new Page<>(search.getPage(),search.getLimit()),wrapper));
    }
    @PutMapping("/addDictionaries")
    public HttpMessage addDictionaries(Dictionaries dictionaries, HttpServletRequest request){
        HttpMessage.isBlank();
        try {
            dictionariesService.save(dictionaries);
            return  HttpMessage.result(ServiceResultEnum.INSERT_TRUE);
        }catch (Exception e){
            LoggerUtil.webError(e,request,log);
            throw new CommonException(ServiceResultEnum.INSERT_ERROR,e);
        }
    }
    @PostMapping("/editDictionaries")
    public HttpMessage editDictionaries(Dictionaries dictionaries, HttpServletRequest request){
        HttpMessage.isBlank();
        try {
            dictionariesService.updateById(dictionaries);
            return  HttpMessage.result(ServiceResultEnum.UPDATE_TRUE);
        }catch (Exception e){
            LoggerUtil.webError(e,request,log);
            throw new CommonException(ServiceResultEnum.UPDATE_ERROR,e);
        }
    }
    @DeleteMapping("/removeDictionaries/{dictionariesNo}")
    public HttpMessage removeDictionaries(@PathVariable Integer dictionariesNo,HttpServletRequest request){
        HttpMessage.isBlank(dictionariesNo);
        try {
            dictionariesService.removeById(dictionariesNo);
            return  HttpMessage.result(ServiceResultEnum.REMOVE_TRUE);
        }catch (Exception e){
            LoggerUtil.webError(e,request,log);
            throw new CommonException(ServiceResultEnum.REMOVE_ERROR,e);
        }

    }
    @DeleteMapping("/batchRemoveDictionaries/{id}")
    public HttpMessage batchRemoveDictionaries(@PathVariable String id){
        HttpMessage.isBlank(id);
        try{
            dictionariesService.removeBatchByIds(Arrays.asList(id.split(",")));
            return  HttpMessage.result(ServiceResultEnum.REMOVE_TRUE);
        }catch (Exception e){
            throw new CommonException(ServiceResultEnum.BATCH_REMOVE_ERROR,e);
        }

    }

    @PostMapping("/batchAddDictionaries")
    public HttpMessage batchAddDictionaries(@RequestParam("dictionaries")List<MultipartFile> dictionaries) {
        dictionaries.forEach(file->{
                try {
                    EasyExcel.read(file.getInputStream(), Dictionaries.class, new DictionariesListener(dictionariesService)).sheet().doRead();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            });
        return  HttpMessage.result(ServiceResultEnum.BATCH_INSERT_TRUE);
    }
        
    @PostMapping("/batchOutDictionaries")
    public void batchOutDictionaries(@RequestParam("dictionaries") List<String> dictionaries, HttpServletResponse response) throws IOException {
        try{
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        //防止乱码
        String fileName ="D:/"+ URLEncoder.encode("dictionariesData:"+LocalDateTime.now().toString(), "UTF-8").replaceAll("\\+", "%20")+".xlsx";
        List<Dictionaries> dictionariesData=new ArrayList<>();
            dictionaries.forEach(item->{
                try {
                    dictionariesData.add( new ObjectMapper().readValue(item,Dictionaries.class));
                } catch (JsonProcessingException e) {
                    throw new RuntimeException(e);
                }
            });
                response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

                EasyExcel.write(response.getOutputStream(), Dictionaries.class).autoCloseStream(Boolean.FALSE).sheet("数据").doWrite(dictionariesData);

        }catch (Exception e){
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");

            response.getWriter().println(HttpMessage.result(ServiceResultEnum.BATCH_OUT_ERROR));
        }
    }
}


